<template>
  <page-dialog
    :title="dialogInfo.title"
    v-model:visible="shows"
    :width="dialogInfo.width"
    :bt-loading="dialogInfo.btLoading"
    :bt-list="dialogInfo.btList"
  >
    <div class="dialog-table">
      <new-page-filter :filter-list="filterInfo.searchBtn">
        <template v-slot:filter-button>
          <div class="dialog-table-header">
            <div class="header-left">
              <div class="lable">资产名称：{{ info.commonName }}</div>
              <div class="lable">可验收数量：{{ info.pendAcceptanceQty }}</div>
            </div>
            <div class="header-right">
              <div class="scan-groups">
                <el-button
                  style="margin-left: 10px"
                  @click="changeNumberAll(true)"
                  >一键验收</el-button
                >
                <el-button
                  style="margin-left: 10px"
                  @click="changeNumberAll(false)"
                  >一键清空</el-button
                >
              </div>
            </div>
          </div>
        </template>
      </new-page-filter>
    </div>
    <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
      <dialog-table
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :check-box="false"
        :pager="false"
        :tab-index="true"
        :handle="tableInfo.handle"
        :listen-height="false"
        :field-list="tableInfo.fieldList"
      >
        <template v-slot:col-qty="scope">
          <el-form-item
            :prop="`data.${scope.$index}.qty`"
            :rules="
              scope.$index >= 0
                ? [
                    {
                      validator: $validate.positive,
                      trigger: ['blur', 'change'],
                    },
                  ]
                : []
            "
          >
            <el-input-number
              v-model="scope.row.qty"
              controls-position="right"
              style="width: 100%; margintop: 18px"
              :min="0"
              :max="info.pendAcceptanceQty"
              :precision="0"
              :step="1"
            />
          </el-form-item>
        </template>
        <template v-slot:col-instructionsValue="scope">
          <select
            v-model.lazy="scope.row.instructions"
            class="select"
            @change="changeSelect($event, 'instructionsValue', scope.row)"
          >
            <option
              v-for="(item, index) in $store.state.permission.dict['has_or_no']"
              :key="index"
              :value="item.code"
            >
              {{ item.name }}
            </option>
          </select>
        </template>
        <template v-slot:col-certificateValue="scope">
          <select
            v-model.lazy="scope.row.certificate"
            class="select"
            @change="changeSelect($event, 'certificateValue', scope.row)"
          >
            <option
              v-for="(item, index) in $store.state.permission.dict['has_or_no']"
              :key="index"
              :value="item.code"
            >
              {{ item.name }}
            </option>
          </select>
        </template>
        <template v-slot:col-warrantyCardValue="scope">
          <select
            v-model.lazy="scope.row.warrantyCard"
            class="select"
            @change="changeSelect($event, 'warrantyCardValue', scope.row)"
          >
            <option
              v-for="(item, index) in $store.state.permission.dict['has_or_no']"
              :key="index"
              :value="item.code"
            >
              {{ item.name }}
            </option>
          </select>
        </template>
        <template v-slot:col-buinessInspectOrderValue="scope">
          <select
            v-model.lazy="scope.row.buinessInspectOrder"
            class="select"
            @change="
              changeSelect($event, 'buinessInspectOrderValue', scope.row)
            "
          >
            <option
              v-for="(item, index) in $store.state.permission.dict['has_or_no']"
              :key="index"
              :value="item.code"
            >
              {{ item.name }}
            </option>
          </select>
        </template>
        <template v-slot:col-inspectionReportValue="scope">
          <select
            v-model.lazy="scope.row.inspectionReport"
            class="select"
            @change="changeSelect($event, 'inspectionReportValue', scope.row)"
          >
            <option
              v-for="(item, index) in $store.state.permission.dict['has_or_no']"
              :key="index"
              :value="item.code"
            >
              {{ item.name }}
            </option>
          </select>
        </template>
      </dialog-table>
    </el-form>
  </page-dialog>
</template>

<script setup name="IndividualDetails">
import _ from 'lodash'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps({
  showDialog: {
    type: Boolean,
  },
  info: {
    type: Object,
    default: function () {
      return {}
    },
  },
})

// 过滤相关配置
const filterInfo = ref({
  searchBtn: [{ slot: true, value: 'button' }],
})
// 表格相关
const tableInfo = ref({
  data: proxy.$fn.deepClone(props.info.details),
  fieldList: [
    { label: '验收数量', value: 'qty', type: 'slot' },
    { label: '说明书', value: 'instructionsValue', type: 'slot' },
    { label: '合格证', value: 'certificateValue', type: 'slot' },
    { label: '保修卡', value: 'warrantyCardValue', type: 'slot' },
    { label: '商检单', value: 'buinessInspectOrderValue', type: 'slot' },
    { label: '检验报告书', value: 'inspectionReportValue', type: 'slot' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '110',
    btList: [
      {
        label: '复制一行',
        event: copyRow,
        show: true,
        ifRender: function (row) {
          return row.qty > 0
        },
      },
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: removeProduct,
        show: true,
        ifRender: ifRenderRemove,
      },
    ],
  },
})
// 弹窗相关
const dialogInfo = ref({
  title: '验收详情',
  width: '90%',
  btLoading: false,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    { label: '保存', event: handleSave, show: true },
  ],
})
const infoData = ref(props.info)

const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emits('update:showDialog', newValue) // 更新父组件showDialog
  },
})
function changeNumberAll(type) {
  if (type) {
    let index = tableInfo.value.data.findIndex(
      (item) =>
        item.instructions == '1' &&
        item.certificate == '1' &&
        item.warrantyCard == '1' &&
        item.buinessInspectOrder == '1' &&
        item.inspectionReport == '1'
    )
    if (index > -1) {
      let data = proxy.$fn.deepClone(tableInfo.value.data[index])
      let sumQty = 0
      tableInfo.value.data.forEach((item) => {
        sumQty = proxy.$fn.accAdd(item.qty || 0, sumQty)
      })
      sumQty = proxy.$fn.Subtr(sumQty, data.qty)
      tableInfo.value.data[index].qty = proxy.$fn.Subtr(
        props.info.pendAcceptanceQty || 0,
        sumQty
      )
    } else {
      let data = proxy.$fn.deepClone(tableInfo.value.data[0])
      data.instructionsValue = '有'
      data.instructions = '1'
      data.certificateValue = '有'
      data.certificate = '1'
      data.warrantyCardValue = '有'
      data.warrantyCard = '1'
      data.buinessInspectOrderValue = '有'
      data.buinessInspectOrder = '1'
      data.inspectionReportValue = '有'
      data.inspectionReport = '1'
      let sumQty = 0
      tableInfo.value.data.forEach((item) => {
        sumQty = proxy.$fn.accAdd(item.qty || 0, sumQty)
      })
      data.qty = proxy.$fn.Subtr(props.info.pendAcceptanceQty || 0, sumQty)
      tableInfo.value.data.unshift(data)
    }
  } else {
    let data = proxy.$fn.deepClone(tableInfo.value.data[0])
    data.qty = 0
    data.instructionsValue = '有'
    data.instructions = '1'
    data.certificateValue = '有'
    data.certificate = '1'
    data.warrantyCardValue = '有'
    data.warrantyCard = '1'
    data.buinessInspectOrderValue = '有'
    data.buinessInspectOrder = '1'
    data.inspectionReportValue = '有'
    data.inspectionReport = '1'
    tableInfo.value.data = [data]
  }
}
function changeSelect(e, str, row) {
  let val = e.target.value
  if (!val) {
    return
  }
  let option = proxy.$store.state.permission.dict['has_or_no']
  let optionItem = option.find((item) => item.code === val)
  row[str] = optionItem.name
}
function copyRow(row, index) {
  let countQty = 0
  tableInfo.value.data.forEach((item) => {
    countQty += item.qty
  })
  if (countQty >= props.info.pendAcceptanceQty) {
    proxy.$message({
      type: 'warning',
      duration: 3500,
      showClose: true,
      message: '验收数量之和不能大于可验收数量，不可再复制！',
    })
    return
  }
  let data = proxy.$fn.deepClone(row)
  data.qty = 1
  // row.qty -= 1
  data.id = tableInfo.value.data.length + Math.random()
  tableInfo.value.data.splice(index + 1, 0, data)
}
function ifRenderRemove() {
  return tableInfo.value.data.length > 1
}
function removeProduct(row) {
  tableInfo.value.data = tableInfo.value.data.filter((item) => item !== row)
}
function handleSave() {
  proxy.$refs['tableForm'].validate((valid) => {
    if (valid) {
      let tableData = proxy.$fn.deepClone(tableInfo.value.data)
      tableData.forEach((item) => {
        item.key = generateProductKey(item)
      })
      let groupList = _.groupBy(tableData, 'key')
      let groupValues = Object.values(groupList)
      let flag = false
      groupValues.forEach((row) => {
        let len = row.length
        if (len > 1) {
          flag = true
        }
      })
      if (flag) {
        proxy.$message({
          type: 'warning',
          duration: 3500,
          showClose: true,
          message: '存在验收相同的数据，请修改！',
        })
        return
      }
      let sumQty = 0
      tableInfo.value.data.forEach((item) => {
        item.calcQty = item.qty || 0
        sumQty = proxy.$fn.accAdd(item.qty || 0, sumQty)
      })
      if (sumQty > props.info.pendAcceptanceQty) {
        proxy.$message({
          type: 'warning',
          duration: 3500,
          showClose: true,
          message: '验收数量之和不能大于可验收数量,请修改！',
        })
        return
      }
      infoData.value.qty = sumQty
      infoData.value.calcQty = sumQty
      infoData.value.details = tableInfo.value.data
      console.log(infoData.value)
      emits('callback', infoData.value)
      handleClose()
    }
  })
}
function generateProductKey(item) {
  let key =
    item.instructions +
    '&' +
    item.certificate +
    '&' +
    item.warrantyCard +
    '&' +
    item.buinessInspectOrder +
    '&' +
    item.inspectionReport
  return key
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
}
</script>

<style scoped lang="scss">
:deep(.filter-item) {
  width: 100%;
}
.text-style {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.select {
  width: 100%;
  height: 28px;
  padding: 0 15px;
  box-sizing: border-box;
  border-radius: 4px;
  color: #606266;
  border: 1px solid #dcdfe6;
}
</style>
